//
//  Data+JW.swift
// @project：JWHelperKit
// @author：linjw(10126121@qq.com)
// @time: 2022/12/20
//  Copyright © 2018年 Linjw. All rights reserved.
//

import Foundation
import UIKit

public extension JWNamespaceWrapper where T == Data {
    
    /// DeviceToken String
    var deviceTokenString: String { return jwWrappedValue.toDeviceTokenText() }
    
    /// Base64字符串
    func toBase64Text() -> String { return jwWrappedValue.base64EncodedString() }
    
    /// 转成json对象
    func toJsonObject(_ jsonReadOptions: JSONSerialization.ReadingOptions = .mutableContainers) -> Any? {
        return try? JSONSerialization.jsonObject(with: jwWrappedValue, options: jsonReadOptions)
    }
    
    /// 生成16进制文本
    func toHexString() -> String {
        let bytes: [UInt8] = Array(jwWrappedValue)
        return bytes.`lazy`.reduce(into: "") {
            var s = String($1, radix: 16)
            if s.count == 1 {
                s = "0" + s
            }
            $0 += s
        }
    }
    
    /// 通过16机制文本，生成Data
    static func create(fromHexString: String) -> Data {
        return Data(hex: fromHexString)
    }
}

extension Data: JWNamespaceWrappable {
    
    fileprivate func toDeviceTokenText() -> String {
        return self.map { String(format: "%02.2hhx", arguments: [$0]) }.joined()
    }
    
}

extension Data {
    
    public init(hex: String) {
        self.init(Array<UInt8>(hex: hex))
    }
    
    public var bytes: Array<UInt8> {
        Array(self)
    }
    
    public func toHexString() -> String {
        self.bytes.toHexString()
    }
    
    mutating func appendByte(_ b: UInt8) {
        var a = b
        self.append(&a, count: 1)
    }
    
}



